/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package XML;

import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author QuangHau
 */
public class SAXFindChunk extends DefaultHandler 
{
    private  boolean start = false;
    private  String id;
    private  String chunk;
    public boolean isYes = false; 
    
    public SAXFindChunk(String _id,String _chunk )
    {
        id = _id;
        chunk = _chunk;
    }

    public void startElement(String namespaceURI,
                             String lName, // local name
                             String qName, // qualified name
                             Attributes attrs)
    throws SAXException
    {
        if(qName.equals("File") && attrs.getValue("id").equals(id))
        {
            start = true;
        }
    }

    public void endElement(String namespaceURI,
                           String sName, // simple name
                           String qName  // qualified name
                          )
    throws SAXException
    {
        if(qName.equals("File"))
        {
            start = false;
        }
    }

    public void characters(char buf[], int offset, int len)
    throws SAXException
    {
        if(start)
        {
            String s = new String(buf, offset, len);
            if(s.equals(chunk))
            {
                isYes = true;
            }
        }
    }
    
    public synchronized static boolean findChunk(String _idFile , String _idChunk)
    {
        boolean res = false;
         // Use an instance of ourselves as the SAX event handler
        SAXFindChunk handler = new SAXFindChunk(_idFile, _idChunk);
        // Use the default (non-validating) parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse( new File("Data.xml"), handler);
            res = handler.isYes;
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return res;
    }
}
